package JXY01;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.Timer;

import static java.util.Objects.*;

public class Aircraft_Battle extends JPanel{
    public static BufferedImage background;
    public static BufferedImage hero0;
    public static BufferedImage hero1;
    public static BufferedImage airplane;
    public static BufferedImage bee;
    public static BufferedImage bullet;
    public static BufferedImage bigplane;
    public static BufferedImage start;
    public static BufferedImage pause;
    public static BufferedImage gameover;
    //英雄机
    //多个敌机
    //多个小蜜蜂。。。

    //定义游戏状态值
    public final int START = 0;
    public final int RUNNING = 1;
    public final int PAUSE = 2;
    public final int GAMEOVER = 3;
    public int state = START;       //游戏状态 Start Running Pause GameOver

    //游戏开始前加载图片
    static {
        try {
            background = ImageIO.read(
                    requireNonNull(Aircraft_Battle.class.getResource("pic/background.png")));
            hero0 = ImageIO.read(
                    requireNonNull(Aircraft_Battle.class.getResource("pic/hero0.png")));
            hero1 = ImageIO.read(
                    requireNonNull(Aircraft_Battle.class.getResource("pic/hero1.png")));
            airplane = ImageIO.read(
                    requireNonNull(Aircraft_Battle.class.getResource("pic/airplane.png")));
            bee = ImageIO.read(
                    requireNonNull(Aircraft_Battle.class.getResource("pic/bee.png")));
            bullet = ImageIO.read(
                    requireNonNull(Aircraft_Battle.class.getResource("pic/bullet.png")));
            bigplane = ImageIO.read(
                    requireNonNull(Aircraft_Battle.class.getResource("pic/bigplane.png")));
            start = ImageIO.read(
                    requireNonNull(Aircraft_Battle.class.getResource("pic/start.png")));
            pause = ImageIO.read(
                    requireNonNull(Aircraft_Battle.class.getResource("pic/pause.png")));
            gameover = ImageIO.read(
                    requireNonNull(Aircraft_Battle.class.getResource("pic/gameover.png")));


        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //一个英雄机
    Hero hero = new Hero();
    //好多子弹
    List<Bullet> bullets = new ArrayList<Bullet>();
    //好多飞行物【敌机大，小/蜜蜂】
    List<FlyingObject> flys = new ArrayList<FlyingObject>();


    Timer timer = new Timer();

    //定时器启动
    public void action(){
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (state == RUNNING) {
                    //生成大小敌机，蜜蜂
                    createFlyObject();
                    //移动方法[敌机，蜜蜂，英雄机]
                    stepAction();
                    //发射子弹
                    shootBullet();

                    //判断子弹撞击飞行物
                    bangAction();
                    //判断英雄机碰撞
                    heroCrash();
                    //判断结束
                    gameOverAction();
                    //判断越界
                    outOfBound();
                }
                //画面刷新
                repaint();

            }
        },10,20);
        MouseAdapter adapter = new MouseAdapter(){          //重写接口，自定义实现功能
            @Override
            public void mouseClicked(MouseEvent e) {
                //单击游戏开始  开始  正在运行  暂停  结束
                if (state == START) {
                    state = RUNNING;
                }
                //重启游戏
                if (state == GAMEOVER){
                    state = START;
                    hero.setLife(3);
                    score = 0;
                }
            }
            public void mouseMoved(MouseEvent e){
                if (state == RUNNING) {
                    //英雄机坐标与鼠标坐标一致
                    super.mouseMoved(e);
                    hero.setX(e.getX() - hero.width / 2);
                    hero.setY(e.getY() - hero.height / 2);
                    repaint();
                }
            }
            //鼠标移出窗口
            public void mouseExited(MouseEvent e){
                if(state == RUNNING) {
                    state = PAUSE;
                }
            }
            //鼠标进入窗口
            public void mouseEntered(MouseEvent e){
                if(state == PAUSE) {
                    state = RUNNING;
                }
            }
        };
        this.addMouseListener(adapter);
        this.addMouseMotionListener(adapter);
        //添加键盘监听器
        KeyAdapter keyAdapter = new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                char c = e.getKeyChar();
                System.out.println(c);
                if (c == '1'){
                    //强制退出
                    System.exit(0);
                }
            }
        };
        this.requestFocus();
        this.addKeyListener(keyAdapter);
    }
    //定时器结束
    private void gameOver(){
        timer.cancel();
    }
    //生成大小敌机，蜜蜂
    private int index = 0;      //计数器，控制飞机出现频率
    private void createFlyObject(){
        index++;
        if (index % 50 == 0){
            index = 0;
            int random = (int)(Math.random() * 6);
            switch (random){
                case 0:
                    flys.add(new Bee());
                    break;
                case 2:
                    flys.add(new Bigplane());
                    break;
                default:
                    flys.add(new Airplane());
            }
        }
    }
    //移动方法
    private void stepAction(){
        //飞行物移动
        for (FlyingObject fly: flys){
            fly.move();
        }
        //子弹移动
        for (Bullet bullet: bullets){
            bullet.move();
        }
        //英雄机移动
        hero.move();

    }
    //发射子弹方法
    int indexBullet = 0;        //控制子弹频率的计数器
    private void shootBullet(){
        indexBullet++;
        if (indexBullet % 30 == 0){
            bullets.addAll(hero.shoot());
        }
    }

    //判断子弹撞击飞行物
    int score = 0;
    private void bangAction(){
        for (int i = 0; i < bullets.size(); i++) {
            for (int j = 0; j < flys.size(); j++){
                FlyingObject fly = flys.get(j);
                boolean isShoot = flys.get(j).shootBy(bullets.get(i));
                    if (isShoot){
                        //撞击到，飞行物移除，子弹移除
                        flys.remove(j);
                        bullets.remove(i);
                        //敌人  加分
                        if (fly instanceof Enemy){
                            score += ((Enemy) fly).getScore();
                        }
                        //奖励  生命/子弹
                        if (fly instanceof Award){
                            int awardType = ((Award) fly).getType();
                            switch (awardType){
                                case Award.DOUBLE_FIRE :
                                    hero.doubleFire();
                                    break;
                                case Award.LIFE :
                                    hero.addLife();
                                    break;
                            }
                        }
                    break;
                }
            }
        }
    }

    //判断英雄机碰撞
    private void heroCrash(){
        for (int i = 0; i < flys.size(); i++) {
            boolean isCrash = hero.crashBy(flys.get(i));
            if (isCrash) {
                //撞击到，飞行物移除，生命值减1
                flys.remove(i);
                hero.setLife(hero.getLife() - 1);
                //生命值为0时游戏结束
                if (hero.getLife() == 0){
                    state = GAMEOVER;
                }
                break;
            }
        }
    }
    //判断结束
    private void gameOverAction(){
//        timer.cancel();

    }
    //判断越界
    private void outOfBound() {
        Iterator<FlyingObject> flysIterator = flys.iterator();
        while (flysIterator.hasNext()) {
            FlyingObject fly = flysIterator.next();
            if (fly.getY() > 650) {             //650为设置的窗口大小
                flysIterator.remove();
            }
        }
        Iterator<Bullet> bulletIterator = bullets.iterator();
        while (bulletIterator.hasNext()) {
            Bullet bullet = bulletIterator.next();
            if (bullet.getY() > 650) {
                flysIterator.remove();
            }
        }
    }
    //画面刷新



    //重写绘图方法
    @Override
    public void paint(Graphics g) {
        super.paint(g);

        g.drawImage(background,0,0,null);
        //画英雄机
        g.drawImage(hero.getImage(),hero.getX(),hero.getY(),null);
        //蜜蜂
        Bee bee = new Bee();
        g.drawImage(bee.getImage(),bee.getX(),bee.getY(),null);
        //敌机
        for (FlyingObject fly: flys) {
            g.drawImage(fly.getImage(), fly.getX(), fly.getY(), null);
        }
        //子弹
        for (Bullet bullet: bullets) {
            g.drawImage(bullet.getImage(), bullet.getX(), bullet.getY(), null);
        }
        //画分数
        g.drawString("分数：" + score,10,20);
        //画退出提示
        g.drawString("按'1'退出游戏",10,630);
        //画生命值
        g.drawString("生命值：" + hero.getLife(),10,40);
        //画游戏状态图片
        switch(state) {
            case START:
                g.drawImage(start, 0, 0, null);							//绘制start图片，坐标（0,0）
                break;
            case PAUSE:
                g.drawImage(pause, 0, 0, null);							//绘制pause图片，坐标（0,0）
                break;
            case GAMEOVER:
                g.drawImage(gameover, 0, 0, null);						//绘制gameover图片，坐标（0,0）
                break;
        }
    }

    public void showMe(){

        //窗口
        JFrame windows = new JFrame("飞机大战");
        //设置大小，关闭选项，位置,置顶,界面大小不可调,去除默认边框等
        windows.setSize(400,650);
        windows.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     //用类调用的静态常量
        windows.setLocationRelativeTo(null);
        windows.setAlwaysOnTop(true);
        windows.setResizable(false);
        windows.setUndecorated(true);
        //面板-绘图
//        JPanel panel = new Aircraft_Battle();
        //画板添加到窗口
        windows.add(this);

        //显示

        windows.setVisible(true);
    }
    public static void main(String[] args){
        //创建界面
        Aircraft_Battle aircraft_battle = new Aircraft_Battle();
        aircraft_battle.showMe();

        aircraft_battle.action();
    }
}
